package com.imooc.liu.shiroimooc.controller;

import com.imooc.liu.shiroimooc.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "myunauthorized";
    }

    @GetMapping("/admin")
    @ResponseBody
    public Map<String, Object> admin() {
        Map<String, Object> map = new HashMap<>();
        map.put("errorCode", "0");
        map.put("message", "admin success");
        return map;
    }

    @GetMapping("/myedit")
    @ResponseBody
    public Map<String, Object> myedit() {
        Map<String, Object> map = new HashMap<>();
        map.put("errorCode", "0");
        map.put("message", "edit success");
        return map;
    }

    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    @PostMapping("/loginUser")
    public String loginUser(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        // 登陆验证
        try {
            subject.login(token);

            // 成功后拿到User对象
            User user = (User) subject.getPrincipal();
            // 存入session中
            session.setAttribute("user", user);
            return "index";
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return "login";
    }

}
